package com.cyw.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyw.common.core.domain.PageQuery;
import com.cyw.common.core.domain.R;
import com.cyw.common.core.page.TableDataInfo;
import com.cyw.common.utils.StringUtils;
import com.cyw.system.domain.TbLabel;
import com.cyw.system.domain.bo.TbLabelBo;
import com.cyw.system.domain.vo.TbLabelVo;
import com.cyw.system.mapper.TbLabelMapper;
import com.cyw.system.service.ITbLabelService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 标签Service业务层处理
 *
 * @author myproject
 * @date 2022-11-22
 */
@RequiredArgsConstructor
@Service
public class TbLabelServiceImpl implements ITbLabelService {

  private final TbLabelMapper baseMapper;

  /** 查询标签 */
  @Override
  public TbLabelVo queryById(Long id) {
    return baseMapper.selectVoById(id);
  }

  /** 查询标签列表 */
  @Override
  public TableDataInfo<TbLabelVo> queryPageList(TbLabelBo bo, PageQuery pageQuery) {
    LambdaQueryWrapper<TbLabel> lqw = buildQueryWrapper(bo);
    Page<TbLabelVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
    return TableDataInfo.build(result);
  }

  /** 查询标签列表 */
  @Override
  public List<TbLabelVo> queryList(TbLabelBo bo) {
    LambdaQueryWrapper<TbLabel> lqw = buildQueryWrapper(bo);
    return baseMapper.selectVoList(lqw);
  }

  private LambdaQueryWrapper<TbLabel> buildQueryWrapper(TbLabelBo bo) {
    Map<String, Object> params = bo.getParams();
    LambdaQueryWrapper<TbLabel> lqw = Wrappers.lambdaQuery();
    lqw.like(StringUtils.isNotBlank(bo.getLabelName()), TbLabel::getLabelName, bo.getLabelName());
    lqw.eq(StringUtils.isNotBlank(bo.getColor()), TbLabel::getColor, bo.getColor());
    return lqw;
  }

  /** 新增标签 */
  @Override
  public Boolean insertByBo(TbLabelBo bo) {
    TbLabel add = BeanUtil.toBean(bo, TbLabel.class);
    validEntityBeforeSave(add);
    boolean flag = baseMapper.insert(add) > 0;
    if (flag) {
      bo.setId(add.getId());
    }
    return flag;
  }

  /** 修改标签 */
  @Override
  public Boolean updateByBo(TbLabelBo bo) {
    TbLabel update = BeanUtil.toBean(bo, TbLabel.class);
    validEntityBeforeSave(update);
    return baseMapper.updateById(update) > 0;
  }

  /** 保存前的数据校验 */
  private void validEntityBeforeSave(TbLabel entity) {
    // TODO 做一些数据校验,如唯一约束
  }

  /** 批量删除标签 */
  @Override
  public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
    if (isValid) {
      // TODO 做一些业务上的校验,判断是否需要校验
    }
    return baseMapper.deleteBatchIds(ids) > 0;
  }

  @Override
  public R<List<TbLabel>> getAll() {
    List<TbLabel> tbLabels = baseMapper.selectList();
    System.out.println(tbLabels);
    return R.ok(tbLabels);
  }
}
